﻿using System;
using System.Collections.Generic;
using Odin.Runners.CommandLine.Resources;

namespace Odin.Runners.CommandLine.Arguments
{
	public class ShowHelp : ArgumentHandler
	{
		public override string Name { get { return "?"; } }
		public override string Description { get { return ArgumentDescriptions.ShowHelp; }}

		private static string[] GetStringsOfSpecificLength(string input, int length)
		{
			if( input.Length <= length )
			{
				return new[] {input};
			}

			var lines = new List<string>();

			var words = input.Split(' ');
			var currentLine = string.Empty;

			foreach( var word in words )
			{
				if( (currentLine.Length + word.Length + 1) > length)
				{
					lines.Add(currentLine.Trim());
					currentLine = string.Empty;
				}
				currentLine += word + " ";
			}
			currentLine = currentLine.Trim();
			if( currentLine.Length > 0 )
			{
				lines.Add(currentLine);
			}

			return lines.ToArray();
		}

		private static void ShowUsage()
		{
			Console.WriteLine("");
			Console.WriteLine("Usage : Odin.Runners.CommandLine [xap file] [options]");
			Console.WriteLine("");
		}

		public override void Execute(string value)
		{
			const int lineStart = 4;
			var longest = 0;

			ShowUsage();

			foreach (var argument in ArgumentManager.Instance.Arguments)
			{
				if( argument.Name.Length > longest )
				{
					longest = argument.Name.Length;
				}
			}

			var descriptionStart = lineStart + longest + 3;
			foreach( var argument in ArgumentManager.Instance.Arguments )
			{
				
				Console.CursorLeft = lineStart;
				Console.Write("/"+argument.Name);
				Console.CursorLeft = descriptionStart;

				var descriptionLines = GetStringsOfSpecificLength(argument.Description, Console.WindowWidth - descriptionStart);
				foreach( var description in descriptionLines )
				{
					Console.CursorLeft = descriptionStart;
					Console.Write(description + "\n");
				}
			}
		}
	}
}
